package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.OverflowListDao;
import com.atguigu.jxc.dao.OverflowListGoodsDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.OverflowList;
import com.atguigu.jxc.entity.OverflowListGoods;
import com.atguigu.jxc.service.OverflowListGoodsService;
import com.atguigu.jxc.util.DateUtil;
import com.atguigu.jxc.util.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OverflowListGoodsServiceImpl implements OverflowListGoodsService {
    @Autowired
    private OverflowListDao overflowListDao;
    @Autowired
    private OverflowListGoodsDao overflowListGoodsDao;
    private Gson gson = new Gson();

    /**
     * 添加报溢单，报溢商品
     *
     * @param overflowList
     * @param overflowListGoodsStr
     * @return
     */
    @Override
    public ServiceVO save(OverflowList overflowList, String overflowListGoodsStr) {
        if (StringUtil.isNotEmpty(overflowListGoodsStr)) {
            overflowList.setUserId(1);
            //添加报溢单
            overflowListDao.save(overflowList);
            //获取报溢单id
            Integer overflowListId =overflowListDao.getByNum(overflowList.getOverflowNumber());
            List<OverflowListGoods> listGoodsList = gson.fromJson(overflowListGoodsStr, new TypeToken<List<OverflowListGoods>>() {
            }.getType());
            //循环遍历报溢商品并添加
            for (OverflowListGoods overflowListGoods : listGoodsList) {
                //设置报溢商品的报溢单id
                overflowListGoods.setOverflowListId(overflowListId);
                log.info(overflowListGoods.toString());
                overflowListGoodsDao.save(overflowListGoods);
            }

            return new ServiceVO(100,"请求成功");
        }else {
            return new ServiceVO(400, "报溢的商品不能为空");
        }
    }

    @Override
    public List<OverflowList> list(String sTime, String eTime) {
        Date start = null;
        Date end = null;
        try {
            String format = "yyyy-MM-dd";
            start = DateUtil.StringToDate(sTime, format);
            end = DateUtil.StringToDate(eTime, format);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return overflowListDao.list(start, end);
    }

    @Override
    public List<OverflowListGoods> goodsList(Integer overflowListId) {
        return overflowListGoodsDao.goodsList(overflowListId);
    }
}
